package com.xu.sso.server.utils;

import com.xu.sso.core.enums.ErrorMessage;
import com.xu.sso.core.exception.SSOException;
import com.xu.sso.core.utils.ExceptionUtil;
import com.xu.sso.server.model.request.OpenApiRequest;
import com.xu.sso.server.model.response.OpenApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;

import java.util.UUID;

public class SignUtil {

    private static Logger log = LoggerFactory.getLogger(SignUtil.class);

    public static OpenApiResponse sign(OpenApiResponse response, OpenApiRequest request, String key) throws SSOException {
        StringBuilder value = new StringBuilder();
        String responseId = UUID.randomUUID().toString();
        value.append("responseId=").append(responseId)
                .append("&appId=").append(request.getAppId())
                .append("&method").append(request.getMethod())
                .append("$content=").append(response.getContent())
                .append("&key=").append(key);
        try {
            String sign = DigestUtils.md5DigestAsHex(value.toString().getBytes("utf-8"));
            response.setResponseId(responseId);
            response.setSign(sign);
            return response;
        } catch (Exception e) {
            log.error(">>>>>>>>>>>>>>>>>>>>>>>SignUtil.sign error===={}", e);
            throw ExceptionUtil.createException(ErrorMessage.SignError);
        }
    }

    public static boolean verifySign(OpenApiRequest request, String key) throws SSOException {
        try {
            StringBuilder value = new StringBuilder();
            value.append("requestId=").append(request.getRequestId())
                    .append("&appId=").append(request.getAppId())
                    .append("&method").append(request.getMethod())
                    .append("$content=").append(request.getContent())
                    .append("&key=").append(key);
            String sign = DigestUtils.md5DigestAsHex(value.toString().getBytes("utf-8"));
            if (sign.equals(request.getSign())) {
                return true;
            }
        } catch (Exception e) {
            log.error(">>>>>>>>>>>>>>>>>>>>>>>SignUtil.verifySign error===={}", e);
        }
        throw ExceptionUtil.createException(ErrorMessage.CheckSignError);
    }

}
